package com.briup.srms.sms.web.controller;

import java.text.SimpleDateFormat;
import java.util.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.briup.srms.sms.bean.StudentAttendance;
import com.briup.srms.sms.bean.extend.StudentAttendanceExtend;
import com.briup.srms.sms.bean.extend.StudentWithAttendance;
import com.briup.srms.sms.service.IStudentAttendanceService;
import com.briup.srms.sms.vm.ClazzAttendance;
import com.jacky.base.utils.ExcelUtils;
import com.jacky.base.utils.Message;
import com.jacky.base.utils.MessageUtil;
import com.jacky.base.utils.PageVM;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * @program: 杰普基础管理系统
 * @description: 学生考勤控制器类
 * @author: charles
 * @create: 2020-12-27 17:22
 **/
@Api(description = "学生考勤相关接口")
@Validated
@RestController
@RequestMapping("/studentAttendance")
public class StudentAttendanceController {

	@Autowired
	private IStudentAttendanceService saService;

	@ApiOperation(value = "查询学生的出勤情况")
	@GetMapping("queryAttendances")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "startTime",required = true, value = "开始时间", paramType = "query"),
		@ApiImplicitParam(name = "endTime",required = true, value = "结束时间", paramType = "query"),
		@ApiImplicitParam(name = "studentId", value = "学生ID", required = true, paramType = "query"),
	})
	public Message queryAttendances(@NotNull Long startTime, @NotNull Long endTime,Long studentId) {
        System.out.println("【queryAttendances】");
        System.out.println("startTime:" + startTime);
        System.out.println("endTime:" + endTime);
        System.out.println("studentId:" + studentId);
		List<StudentAttendance> list = saService.queryAttendances(startTime,endTime,studentId);
		return MessageUtil.success(list);
	}

	@ApiOperation(value = "通过ID删除考勤信息")
	@GetMapping("deleteById")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "id", value = "考勤ID", required = true, paramType = "query"),
	})
	public Message deleteById(@NotNull int id) {
        System.out.println("【deleteById】");
		saService.deleteById(id);
		return MessageUtil.success("删除成功");
	}


	@ApiOperation(value = "保存考勤信息",notes="一次性提交多天的考勤信息")
	@PostMapping("batchSaveMulti")
	public Message batchSave(Long[] ids,Long[] dates, String[] stages,String status,String comment){
        System.out.println("————————【batchSave】————————————");
        System.out.println(Arrays.toString(ids));
        System.out.println(Arrays.toString(dates));
        System.out.println(Arrays.toString(stages));
        System.out.println(status);
        System.out.println(comment);
        System.out.println("————————batchSave end————————————");
		saService.batchSaveMulti(ids,dates,stages,status,comment);
		return MessageUtil.success("操作成功!");
	}

	@ApiOperation(value = "保存考勤信息")
	@PostMapping("batchSave")
	public Message batchSave(Long[] ids,Long date, String stage,String status,String comment){
        System.out.println("【batchSave】");
		saService.batchSave(ids,date,stage,status,comment);
		return MessageUtil.success("操作成功!");
	}

	@ApiOperation(value = "查询院系考勤报表，用于月报周报汇报")
	@GetMapping("pageQueryAttendanceReport")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "page", value = "当前页", required = true, paramType = "query"),
		@ApiImplicitParam(name = "pageSize", value = "每页大小", required = true, paramType = "query"),
		@ApiImplicitParam(name = "channelId", value = "渠道编号", paramType = "query"),
		@ApiImplicitParam(name = "directionId", value = "杰普方向编号", paramType = "query"),
		@ApiImplicitParam(name = "clazzId", value = "杰普班级编号", paramType = "query"),
		@ApiImplicitParam(name = "startTime",required = true, value = "开始时间", paramType = "query"),
		@ApiImplicitParam(name = "endTime",required = true, value = "结束时间", paramType = "query"),
	})
	public Message pageQueryAttendanceReport(@NotNull int page,@NotNull int pageSize, Long channelId,
			Long directionId, Long clazzId,@NotNull Long startTime, @NotNull Long endTime) {
        System.out.println("【pageQueryAttendanceReport】");
        System.out.println(page);
        System.out.println(pageSize);
        System.out.println(channelId);
        System.out.println(directionId);
        System.out.println(clazzId);
        System.out.println(startTime);
        System.out.println(endTime);
        System.out.println("【pageQueryAttendanceReport end】");
		PageVM<StudentWithAttendance> pageVM = saService.pageQueryAttendanceReport(page, pageSize, channelId, directionId, clazzId, startTime, endTime);
		return MessageUtil.success(pageVM);
	}

	@ApiOperation(value = "查询考勤信息")
	@GetMapping("pageQuery")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "page", value = "当前页", required = true, paramType = "query"),
		@ApiImplicitParam(name = "pageSize", value = "每页大小", required = true, paramType = "query"),
		@ApiImplicitParam(name = "realname", value = "姓名", paramType = "query"),
		@ApiImplicitParam(name = "directionId", value = "杰普方向编号", paramType = "query"),
		@ApiImplicitParam(name = "clazzId", value = "杰普班级编号", paramType = "query"),
		@ApiImplicitParam(name = "status", value = "状态", paramType = "query"),
		@ApiImplicitParam(name = "attendanceDateStr", value = "出勤时间字符串", paramType = "query"),
	})
	public Message pageQuery(@NotNull int page, @NotNull int pageSize,String realname,Long directionId,Long clazzId,String status,String attendanceDateStr){
        System.out.println("------------【pageQueryAttendance】-------------");
        System.out.println(page);
        System.out.println(pageSize);
        System.out.println(realname);
        System.out.println(directionId);
        System.out.println(clazzId);
        System.out.println(status);
        System.out.println(attendanceDateStr);
        System.out.println("------------------------");
		String[] statuses = null;
		if(status!=null && !StringUtils.isEmpty(status)) {
			statuses = new String[] {status};
		}

		PageVM<StudentAttendanceExtend> pagevm = saService.pageQuery(page, pageSize,realname,directionId,clazzId,statuses,attendanceDateStr);
        //System.out.println("【size】：" + pagevm.getList().size());
		return MessageUtil.success(pagevm);
	}


	@ApiOperation(value = "查询实训学生的考勤信息")
	@GetMapping("pageQueryTrain")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "page", value = "当前页", required = true, paramType = "query"),
		@ApiImplicitParam(name = "pageSize", value = "每页大小", required = true, paramType = "query"),
		@ApiImplicitParam(name = "realname", value = "姓名", paramType = "query"),
		@ApiImplicitParam(name = "trainId", value = "实训编号", paramType = "query"),
		@ApiImplicitParam(name = "channelId", value = "渠道编号", paramType = "query"),
		@ApiImplicitParam(name = "attendanceDateStr", value = "出勤时间字符串", paramType = "query"),
	})
	public Message pageQueryTrain(@NotNull int page,@NotNull  int pageSize,String realname,Long trainId,Long channelId,String attendanceDateStr) {
        System.out.println("【pageQueryTrain】");
		PageVM<StudentAttendanceExtend> pageVM = saService.pageQueryTrain(page,pageSize,realname,trainId,channelId,attendanceDateStr);
		return MessageUtil.success(pageVM);
	}

	@ApiOperation(value = "查询班级考勤信息")
	@GetMapping("queryClazzAttendance")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "date", value = "当前日期", required = true, paramType = "query"),
		@ApiImplicitParam(name = "stage", value = "阶段", required = true, paramType = "query"),
		@ApiImplicitParam(name = "area", value = "基地", required = true, paramType = "query"),
		@ApiImplicitParam(name = "status", value = "状态", required = true, paramType = "query"),
		@ApiImplicitParam(name = "chargeId", value = "班主任编号", required = true, paramType = "query")
	})
	public Message queryClazzAttendance(@NotNull Long date,@NotNull String stage,String area,String status,Long chargeId) {
        System.out.println("【queryClazzAttendance】");
        System.out.println(date);
        System.out.println(stage);
        System.out.println(area);
        System.out.println(status);
        System.out.println(chargeId);
		List<ClazzAttendance> list = saService.queryClazzAttendance(date, stage,area,status,chargeId);
		return MessageUtil.success(list);
	}

	@ApiOperation(value = "班级考勤信息导入到Excel中", notes = "注意！测试的时候请将地址粘贴到浏览器地址栏测试", produces = "application/octet-stream")
	@GetMapping("downloadClazzAttendance")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "date", value = "当前日期", required = true, paramType = "query"),
		@ApiImplicitParam(name = "stage", value = "阶段", required = true, paramType = "query"),
		@ApiImplicitParam(name = "area", value = "基地", required = true, paramType = "query"),
		@ApiImplicitParam(name = "status", value = "状态", required = true, paramType = "query"),
		@ApiImplicitParam(name = "chargeId", value = "班主任编号", required = true, paramType = "query")
	})
	public void downloadClazzAttendance(HttpServletResponse response,@NotNull Long date
			,@NotNull String stage,String area,String status,Long chargeId) throws Exception {
        System.out.println("【downloadClazzAttendance】");
		// 2. 将excel导出
		// 2.1 excel头部数据
		String[] headList = new String[] { "序号","基地", "教室", "班级","生源","开班时间", "结课时间","班主任","主讲老师","辅导老师","课程","总人数", "离校人数","应到人数","缺勤人数","实到人数","考勤情况","备注"};
		// 2.2 属性
		String[] fieldList = new String[] { "index","area","clazzRoom", "clazz","source","beginTime","endTime", "charge", "mainTeacher",
				"assistTeacher","course","total","leaveNum","shouldNum", "absenceNum","actualNum","introduce","comment"};
		// 2.3 数据列，需要转化
		List<Map<String, Object>> dataList = new ArrayList<>();
		List<ClazzAttendance> list = saService.queryClazzAttendance(date, stage,area,status,chargeId);
		SimpleDateFormat formatter = new SimpleDateFormat ("yyyy-MM-dd");
		for (int i=0;i<list.size();i++) {
			ClazzAttendance u = list.get(i);
			Map<String, Object> map = new HashMap<>();
			map.put("index", i+1);
			map.put("clazz", u.getClazz() !=null ? u.getClazz().getName():"");
			// 开学时间，结束时间
			if(u.getClazz()!=null) {
				if(u.getClazz().getBeginTime()!=null) {
					map.put("beginTime", u.getClazz() !=null ? formatter.format( u.getClazz().getBeginTime()):"" );
				} else {
					map.put("beginTime", "" );
				}
				if(u.getClazz().getEndTime()!=null) {
					map.put("endTime", u.getClazz() !=null ? formatter.format( u.getClazz().getEndTime()):"" );
				} else {
					map.put("endTime", "" );
				}
			}
			map.put("area", u.getClazz() !=null ?u.getClazz().getArea():"");
			map.put("charge",  u.getClazz() !=null ?( u.getClazz().getCharge()!=null?u.getClazz().getCharge().getRealname():"未指派"):"");
			map.put("clazzRoom", u.getClazz() !=null ?  (u.getClazz().getClazzRoom()!=null?u.getClazz().getClazzRoom().getName():""):"未指定");
			map.put("introduce", u.getIntroduce());
			map.put("mainTeacher", u.getClazzLog()!=null? u.getClazzLog().getMainTeacher():"");
			map.put("assistTeacher", u.getClazzLog()!=null? u.getClazzLog().getAssistTeacher():"");
			map.put("course",u.getClazzLog()!=null? u.getClazzLog().getCourse():"");
			map.put("source", u.getClazz()!=null? u.getClazz().getSource():"");
			// 人数
			map.put("absenceNum",u.getAbsenceNum() );	// 缺勤
			map.put("shouldNum",u.getClazz()!=null?u.getClazz().getTotal() - u.getClazz().getLeaveNum():"");	// 应到
			map.put("leaveNum",u.getClazz()!=null?u.getClazz().getLeaveNum():"");		// 离校人数
			map.put("actualNum",u.getClazz()!=null?(u.getClazz().getTotal() - u.getClazz().getLeaveNum())-u.getAbsenceNum():"");		// 实到人数
			map.put("total",  u.getClazz() !=null ? u.getClazz().getTotal():"");	// 总人数

			map.put("comment", u.getClazzLog()!=null? u.getClazzLog().getComment():"");
			dataList.add(map);
		}
		// 2.4 导出文件名
		String excelName = "clazz_attendance_"+formatter.format(new Date().getTime());
		// 3. 调用工具方法导出Excel
		ExcelUtils.createExcel(response, excelName, headList, fieldList, dataList);

	}

	@ApiOperation(value = "导出院系考勤报表，用于月报周报汇报", notes = "注意！测试的时候请将地址粘贴到浏览器地址栏测试", produces = "application/octet-stream")
	@GetMapping("downloadStudentAttendance")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "page", value = "当前页", required = true, paramType = "query"),
		@ApiImplicitParam(name = "pageSize", value = "每页大小", required = true, paramType = "query"),
		@ApiImplicitParam(name = "channelId", value = "渠道编号", paramType = "query"),
		@ApiImplicitParam(name = "directionId", value = "杰普方向编号", paramType = "query"),
		@ApiImplicitParam(name = "clazzId", value = "杰普班级编号", paramType = "query"),
		@ApiImplicitParam(name = "startTime",required = true, value = "开始时间", paramType = "query"),
		@ApiImplicitParam(name = "endTime",required = true, value = "结束时间", paramType = "query"),
	})
	public void downloadStudentAttendance(HttpServletResponse response,@NotNull int page,@NotNull int pageSize, Long channelId,
			Long directionId, Long clazzId,@NotNull Long startTime, @NotNull Long endTime) throws Exception {
        System.out.println("【downloadStudentAttendance】");
		// 2. 将excel导出
		// 2.1 excel头部数据
		String[] headList = new String[] { "专业", "姓名", "学习方向","考勤情况" ,"基地名称"};
		// 2.2 属性
		String[] fieldList = new String[] {  "major","student", "direction","comment","baseName"};
		// 2.3 数据列，需要转化
		List<Map<String, Object>> dataList = new ArrayList<>();
		PageVM<StudentWithAttendance> pageVM = saService.pageQueryAttendanceReport(page, pageSize, channelId, directionId, clazzId, startTime, endTime);
		SimpleDateFormat formatter = new SimpleDateFormat ("yyyy-MM-dd");
		List<StudentWithAttendance> list = pageVM.getList();
		for (int i=0;i<list.size();i++) {
			StudentWithAttendance u = list.get(i);
			Map<String, Object> map = new HashMap<>();
			map.put("major", u.getMajor());
			map.put("student", u.getRealname());
			map.put("direction", u.getDirection());
			map.put("comment", StringUtils.collectionToCommaDelimitedString(u.getAttendances()));
			map.put("baseName", "杰普软件");
			dataList.add(map);
		}
		// 2.4 导出文件名
		String excelName = "clazz_attendance_"+formatter.format(new Date().getTime());
		// 3. 调用工具方法导出Excel
		ExcelUtils.createExcel(response, excelName, headList, fieldList, dataList);

	}


}
